﻿using System;
using System.Threading;

namespace CatUtils.Utils.Enhance.ThreadTool
{
    /// <summary>
    /// 线程阻塞，随机休眠帮助
    /// </summary>
    public static class ThreadSleep
    {
        /// <summary>
        /// 按秒设置睡眠时间
        /// </summary>
        /// <param name="MaxTime"></param>
        /// <param name="ProgressLog"></param>
        public static void SetSecondClock(int MaxTime, bool ProgressLog = true)
        {
            SleepLog(MaxTime);
        }

        /// <summary>
        /// 按毫秒设置睡眠时间
        /// </summary>
        /// <param name="MaxTime"></param>
        public static void SetMillisecondClock(int MaxTime)
        {
            Thread.Sleep(MaxTime);
        }

        /// <summary>
        /// 按毫秒设置睡眠时间
        /// </summary>
        /// <param name="MinTime"></param>
        /// <param name="MaxTime"></param>
        /// <param name="ProgressLog"></param>
        public static void RandomMillisecondClock(int MinTime, int MaxTime, bool ProgressLog = true)
        {
            int SleepRandom = new Random().Next(MinTime, MaxTime);
            if (ProgressLog)
                Console.WriteLine($"休眠{SleepRandom}毫秒，由于时间过于琐碎不再打印日志。");
            Thread.Sleep(SleepRandom);
        }

        /// <summary>
        /// 按秒设置睡眠时间
        /// </summary>
        /// <param name="MinTime"></param>
        /// <param name="MaxTime"></param>
        /// <param name="ProgressLog"></param>
        public static void RandomSecondClock(int MinTime, int MaxTime, bool ProgressLog = true)
        {
            int SleepRandom = new Random().Next(MinTime, MaxTime);

            SleepLog(SleepRandom);
        }

        /// <summary>
        /// 更新进度和打印
        /// </summary>
        /// <param name="SleepTime"></param>
        /// <param name="ProgressLog"></param>
        private static void SleepLog(int SleepTime, bool ProgressLog = true)
        {
            while (SleepTime >= 0)
            {
                if (ProgressLog)
                    Console.WriteLine(string.Format("{0} 程序休眠中，距离唤醒还有{1}秒。", DateTime.Now.ToString(), SleepTime--), 0, 0);

                Thread.Sleep(1000);
            }
        }
    }
}